package com.example.demo_mysql_mybatisplus.configs.async.trans.context;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@RestController
@RequestMapping("async/trans/context")
public class AsyncTransContextController {
    @Autowired
    Service_1 service_1;

    // 异步线程传递上下文
    @GetMapping("/test")
    public void test(){

        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        attributes.setAttribute("attribute_1","val000001",1);

        service_1.method_1();
        service_1.method_2();
    }
}

@Service
class Service_1 {

    public void method_1(){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        System.out.println( Thread.currentThread().getName()+ ",in method_1 :"
                +attributes.getAttribute("attribute_1",1) );
    }

    @Async
    public void method_2(){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        // 没有实现AsyncConfigurer，则attributes在异步线程中为null
        System.out.println( Thread.currentThread().getName()+ ",in method_2 :"
                +attributes.getAttribute("attribute_1",1) );
    }

}